package mumu.android.lib.localstorage;

import java.io.File;
import java.io.IOException;

import mumu.android.lib.tool.Tools;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

/**
 * SQLiteOpenHelper 提供了默认的数据库处理，并且这些数据库必须保存在/data/data/<package
 * name>/databases目录下，但是在一些需求中，需要将数据库存储在sd卡上。这就不能使用这个类库，而需要自定义一个方法
 * 来实现这个功能。以下就是这样一个类。提供了数据库升级、创建相关的功能。
 * 
 * @author Administrator
 * 
 */
public class FileSQLiteOpenHelper {
	private static final String DB_DIR = Tools.getSDPath() + "/ssss/ssss/";
	private static final String DB_NAME = DB_DIR + "dd.db";
	private static final int DB_VERSION = 2;
	private static FileSQLiteOpenHelper instance;
	private final Context mContext;

	public synchronized static FileSQLiteOpenHelper getInstance(Context context) {
		if (instance == null) {
			instance = new FileSQLiteOpenHelper(context);
		}
		return instance;
	}

	private FileSQLiteOpenHelper(Context mContext) {
		this.mContext = mContext;
	}

	public SQLiteDatabase getDb() {
		return createDbFileOnSDCard();
	}

	private SQLiteDatabase createDbFileOnSDCard() {
		SQLiteDatabase result = null;

		File dbFile = new File(DB_NAME);
		File dir = new File(DB_DIR);
		boolean dbFileExists = dbFile.exists();
		if(!dir.exists()){
			dir.mkdirs();
		}
		
		result = SQLiteDatabase.openOrCreateDatabase(dbFile, null);

		if (result != null) {
			// 第一次创建数据库
			if (!dbFileExists) {
				onCreate(result);
			}

			int oldVersion = result.getVersion();
			int newVersion = DB_VERSION;
			// 更新数据库
			if (oldVersion != newVersion) {
				if (dbFileExists) {
					onUpgrade(result, oldVersion, newVersion);
				}
				result.setVersion(newVersion);
			}
		}

		return result;
	}

	public void onCreate(SQLiteDatabase db) {
		db.execSQL("create table hosp (hosp_id varchar(50) primary key,alias varchar(20),photo varchar(300),city_code varchar(10))");
	}

	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	public static void closeDatabase() {
		if (instance != null) {
			instance = null;
		}
	}

}
